package com.oa.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.oa.server.entity.Employee;
import com.oa.server.entity.RespPageBean;
import com.oa.server.mapper.EmployeeMapper;
import com.oa.server.result.ResponseBean;
import com.oa.server.service.IEmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author mcy
 * @since 2021-06-01
 */
@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements IEmployeeService {


    /**
     *
     */
    @Autowired
    private EmployeeMapper employeeMapper;
    @Override
    public RespPageBean getAllEmployeesByPage(Integer currentPage, Integer pageSize, Employee employee, LocalDate[] beginDateScope) {
        //开启一个分页
        Page<Employee> page = new Page<>(currentPage,pageSize);
        IPage<Employee> employeeIPage = employeeMapper.getEmployeesByPage(page,employee,beginDateScope);
        RespPageBean responseBean = new RespPageBean(employeeIPage.getTotal(),employeeIPage.getRecords());
        return responseBean ;
    }

    @Override
    public ResponseBean getMaxWorkID() {
        List<Map<String, Object>> maps = employeeMapper.selectMaps(new QueryWrapper<Employee>().select("max(workID)"));
        int maxWorkID = Integer.parseInt((String) maps.get(0).get("max(workID)"));
        //得到最大的工号+1
        return ResponseBean.success( String.format("%08d",maxWorkID+1));
    }

    @Override
    public ResponseBean addEmployee(Employee employee) {
        // 处理合同期限 保留两位小数
        LocalDate beginContract = employee.getBeginContract();
        LocalDate endContract = employee.getEndContract();
        long days = beginContract.until(endContract, ChronoUnit.DAYS);
        DecimalFormat decimalFormat = new DecimalFormat("##.00");
        employee.setContractTerm(Double.parseDouble(decimalFormat.format(days/365.00)));
        if(1==employeeMapper.insert(employee)){
            return ResponseBean.success("添加成功");
        }
        return ResponseBean.error("添加失败");
    }

    /**
     * 查询员工
     * @param id
     * @return
     */
    @Override
    public List<Employee> getEmployee(Integer id)
    {
        return employeeMapper.getEmployee(id);
    }
}
